package com.mocoop.plugin.file;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONException;

import android.content.Intent;

import cn.imeth.android.camera.CameraActivity;
import cn.imeth.android.image.choose.PhotoChooseActivity;

import com.google.gson.Gson;
import com.mocoop.plugin.MocoopPlugin;
import com.mocoop.ui.ActionSheet;
import com.mocoop.ui.ActionSheet.ActionSheetListener;

public class MyFileChooser extends MocoopPlugin {

	private CallbackContext callbackContext;

	@Override
	public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

		this.callbackContext = callbackContext;

		ActionSheet.createBuilder(getActivity(), getActivity().getFragmentManager())
        .setCancelButtonTitle("取消")
        .setOtherButtonTitles(new String[]{"拍照","相册"})
        .setCancelableOnTouchOutside(true)
        .setListener(new ActionSheetListener() {
			
			@Override
			public void onOtherButtonClick(ActionSheet actionSheet, int index) {
				if(index==0){
					openCamera();
				}else {
					openImgChooser();
				}
			}
			
			@Override
			public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
			
			}
		}).show();
		
		return true;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 34) {
			if (intent != null && intent.getStringArrayExtra("photos") != null) {
				String[] imgPaths = intent.getStringArrayExtra("photos");
				if (callbackContext != null)
					callbackContext.success(new Gson().toJson(imgPaths));
			}
		}else if(requestCode == 35){
			if(intent == null||intent.getData()==null) return;
			String imgPath = intent.getData().getPath();
			if(callbackContext!=null)
			callbackContext.success(new Gson().toJson(new String[]{"file://" + imgPath}));
		}
	}

	private void openImgChooser() {
		Intent intent = new Intent(cordova.getActivity(), PhotoChooseActivity.class);
		cordova.startActivityForResult((CordovaPlugin) this, intent, 34);
	}

	private void openCamera() {
		Intent intent = new Intent(cordova.getActivity(), CameraActivity.class);
		intent.putExtra("square", false);
		cordova.startActivityForResult((CordovaPlugin) this, intent, 35);
	}
}
